/*
 * @Author: lin.zehong
 * @Date: 2019-07-22 09:57:51
 * @Last Modified by: lin.zehong
 * @Last Modified time: 2019-07-22 11:02:16
 * @Desc: 新增标签、使用对象；model queryLabelByName 方法，因为需求 搜索 和 树选中 没有关系，
 *        则，分页需要记住之前的状态，是搜索下的分页，还是树选中之后的分页，
 *        这个在 model 中做了处理。
 */
import React, { Component } from "react";
import { connect } from "dva";
import { Modal, Divider, Tree, Table, Input, Spin } from "antd";
import styles from "./SelectModal.less";

const { DirectoryTree, TreeNode } = Tree;
const { Search } = Input;

@connect(({ personSelectModel, adddataSource }) => ({
  personSelectModel,
  adddataSource
}))
class SelectModal extends Component {
  state = { selectedRowKeys: [], selectCache: [], selectedRowDesc: [] };

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: "personSelectModel/clearData",
    });
  }

  sexMap = {
    1: "男",
    2: "女"
  };

  userTypeMap = {
    10: "民警",
    15: "现役",
    20: "辅警",
    25: "在编人员",
    30: "外部人员"
  };

  partTypeMap = {
    10: "兼职",
    20: "挂职",
    25: "返聘",
    30: "在职"
  };

  columns = [
    { title: "姓名", dataIndex: "userName", width: "15%" },
    // { title: "身份证号码", dataIndex: "userCode", width: "20.5%" },
    // { title: "警号", dataIndex: "userPoliceId", width: "20.5%" },
    { title: "所属机构", dataIndex: "orgName" },
    {
      title: "性别",
      dataIndex: "userSex",
      width: "8%",
      render: text => this.sexMap[text]
    },
    // {
    //   title: "身份类型",
    //   dataIndex: "userType",
    //   width: "12%",
    //   render: text => this.userTypeMap[text]
    // },
    {
      title: "岗位情况",
      dataIndex: "userPartType",
      width: "12%",
      render: text => this.partTypeMap[text]
    }
  ];

  static getDerivedStateFromProps(props, state) {
    if (props.select !== state.selectCache) {
      return {
        selectedRowKeys: props.select,
        selectCache: props.select,
        selectedRowDesc: props.selectdesc
      };
    }
    return null;
  }

  // 树点击查询
  onSelect = value => {
    this.props.dispatch({
      type: "personSelectModel/queryLabelByName",
      payload: {
        orgCode: value[0],
        isOrg: true,
      }
    });
  };

  renderTreeNodes = data => (data || []).map(item => {
    if (item.children.length > 0) {
      return (
        <TreeNode title={item.title} key={item.code} dataRef={item}>
          {this.renderTreeNodes(item.children)}
        </TreeNode>
      );
    }
    return (
      <TreeNode title={item.title} key={item.code} dataRef={item} isLeaf />
    );
  });

  search = value => {
    this.props.dispatch({
      type: "personSelectModel/queryLabelByName",
      payload: {
        content: value,
        isSearch: true,
      }
    });
  };

  render() {
    const { adddataSource, personSelectModel, manager, reporter, title, disableChecked = false } = this.props;
    const { orgTree = [] } = adddataSource;
    const { selectedRowKeys, selectedRowDesc } = this.state;
    const {
      datas,
      totalCount,
      // totalPage,
      pageNum,
      loading
    } = personSelectModel;

    const rowSelection1 = {
      type: "radio",
      selectedRowKeys,
      onChange: (selectedRowKeyss, selectedRows) => {
        this.setState({
          selectedRowKeys: selectedRowKeyss,
          selectedRowDesc: [selectedRows[0].userName]
        });
      },
      getCheckboxProps: () => ({
        disabled: disableChecked, // Column configuration not to be checked
      }),
    };
    const rowSelection2 = {
      selectedRowKeys,
      onSelect: (record, selected) => {
        this.setState(prevState => {
          const selectedRowKeysTemp = JSON.parse(
            JSON.stringify(prevState.selectedRowKeys || [])
          );
          const selectedRowDescTemp = JSON.parse(
            JSON.stringify(prevState.selectedRowDesc || [])
          );
          if (selected === true) {
            selectedRowKeysTemp.push(record.userCode);
            selectedRowDescTemp.push(record.userName);
          } else {
            const index = selectedRowKeysTemp.findIndex(
              item => item === record.userCode
            );
            selectedRowKeysTemp.splice(index, 1);
            selectedRowDescTemp.splice(index, 1);
          }
          return {
            selectedRowKeys: selectedRowKeysTemp,
            selectedRowDesc: selectedRowDescTemp
          };
        });
      },
      onSelectAll: (selected, selectedRows) => {
        this.setState(prevState => {
          const selectedRowKeysTemp = JSON.parse(
            JSON.stringify(prevState.selectedRowKeys || [])
          );
          const selectedRowDescTemp = JSON.parse(
            JSON.stringify(prevState.selectedRowDesc || [])
          );
          if (selected === true) {
            selectedRows.forEach(item => {
              selectedRowKeysTemp.push(item.userCode);
              selectedRowDescTemp.push(item.userName);
            });
          } else {
            selectedRows.forEach(items => {
              const index = selectedRowKeysTemp.findIndex(
                item => item === items.userCode
              );
              selectedRowKeysTemp.splice(index, 1);
              selectedRowDescTemp.splice(index, 1);
            });
          }
          return {
            selectedRowKeys: selectedRowKeysTemp,
            selectedRowDesc: selectedRowDescTemp
          };
        });
      },
      getCheckboxProps: () => ({
        disabled: disableChecked, // Column configuration not to be checked
      }),
    };

    const getTitle = () => {
      if (reporter) {
        return "请选择告警目标";
      }
      if (manager) {
        return "请选择管理员";
      }
      return "选择推送对象";
    };
    return (
      <Modal
        title={title || getTitle()}
        maskClosable={false}
        visible={this.props.visible}
        onOk={() => {
          this.props.confirm(selectedRowKeys, selectedRowDesc);
          this.setState({ selectCache: selectedRowKeys });
        }}
        onCancel={this.props.closeModal}
        width="1050px"
      >
        <div className={styles.content}>
          <div className={styles.left}>
            <DirectoryTree
              onSelect={value => this.onSelect(value)}
              onExpand={this.onExpand}
            >
              {this.renderTreeNodes(orgTree)}
            </DirectoryTree>
          </div>
          <Divider type="vertical" className={styles.divider} />
          <div className={styles.right}>
            <Search
              placeholder="搜索"
              className={styles.search}
              onSearch={value => this.search(value)}
            />
            <Spin spinning={loading} delay={300}>
              <Table
                columns={this.columns}
                dataSource={datas}
                rowKey={record => record.userCode}
                rowSelection={
                  this.props.isMutiple ? rowSelection2 : rowSelection1
                }
                size="middle"
                pagination={{
                  total: totalCount,
                  pageSize: 5,
                  current: pageNum,
                  onChange: pageNumber => {
                    this.props.dispatch({
                      type: "personSelectModel/queryLabelByName",
                      payload: {
                        pageNum: pageNumber,
                        isPagination: true,
                      }
                    });
                  },
                  showTotal: total =>
                    `共 ${total} 条记录 第 ${pageNum}/ ${Math.ceil(
                      total / 5
                    )}页`
                }}
              />
            </Spin>
          </div>
        </div>
      </Modal>
    );
  }
}

export default SelectModal;
